import json
import os
from gi.repository import GObject

class RadioManager(GObject.GObject):
    __gsignals__ = {
        'categories-loaded': (GObject.SignalFlags.RUN_FIRST, None, ()),
        'stations-loaded': (GObject.SignalFlags.RUN_FIRST, None, (str,)),
        'cover-changed': (GObject.SignalFlags.RUN_FIRST, None, (str,))
    }

    def __init__(self):
        super().__init__()
        self.categories = []
        self.stations = {}
        self.favorites = []
        self.current_station = None
        self._load_data()

    def _load_data(self):
        # 加载分类数据
        with open('data/categories.json') as f:
            self.categories = json.load(f)
            self.emit('categories-loaded')

        # 加载电台数据
        with open('data/radio_data.json') as f:
            self.stations = json.load(f)
        
        # 加载收藏数据
        if os.path.exists('data/favorites.json'):
            with open('data/favorites.json') as f:
                self.favorites = json.load(f)

    def get_stations_by_category(self, category_id):
        return [s for s in self.stations if s['category'] == category_id]

    def add_favorite(self, station_id):
        if station_id not in self.favorites:
            self.favorites.append(station_id)
            self._save_favorites()

    def remove_favorite(self, station_id):
        if station_id in self.favorites:
            self.favorites.remove(station_id)
            self._save_favorites()

    def _save_favorites(self):
        with open('data/favorites.json', 'w') as f:
            json.dump(self.favorites, f)

    def get_cover_path(self, station_id):
        covers_dir = 'src/assets/covers'
        # 查找匹配的封面文件
        for ext in ['.png', '.jpg']:
            cover_path = os.path.join(covers_dir, f"{station_id}{ext}")
            if os.path.exists(cover_path):
                return cover_path
        return os.path.join(covers_dir, 'default.png')